package com.sjb.mianshiya.satoken;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.sjb.mianshiya.exception.ThrowUtils;
import com.sjb.mianshiya.mapper.common.ErrorCode;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:sjb
 * @CreateTime:2024-11-21
 * @Description: 获取设备信息工具类
 * @Version：1.0
 */
public class DeviceUtil {


    /**
     * 根据请求获取设备信息
     * @param request
     * @return
     */
    public static String getRequestDevice(HttpServletRequest request) {
        String userAgentStr = request.getHeader(Header.USER_AGENT.toString());
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        ThrowUtils.throwIf(userAgent == null, ErrorCode.NO_AUTH_ERROR,"非法请求");

        // 默认为PC
        String device = "pc";
        if (isMiniProgram(userAgentStr)){
            device = "miniProgram";
        }else if (isPad(userAgentStr)) {
            device = "pad";
        }else if (userAgent.isMobile()){
            device = "mobile";
        }
        return device;
    }


    /**
     * 判断是否是微信小程序
     * @param userAgentStr
     * @return
     */
    public static boolean isMiniProgram(String userAgentStr){
        // 判断 User-Agent 是否包含 "MicroMessenger" 表示是微信环境
        return StrUtil.containsIgnoreCase(userAgentStr, "MicroMessenger")
                && StrUtil.containsIgnoreCase(userAgentStr, "MiniProgram");
    }

    /**
     * 判断是否是平板设备
     * @param userAgentStr
     * @return
     */
    public static boolean isPad(String userAgentStr){

        boolean isIpad = StrUtil.containsIgnoreCase(userAgentStr, "iPad");

        // 检查 Android 平板（包含 "Android" 且不包含 "Mobile"）
        boolean isAndroidTablet = StrUtil.containsIgnoreCase(userAgentStr, "Android")
                && !StrUtil.containsIgnoreCase(userAgentStr, "Mobile");

        // 如果是 iPad 或 Android 平板，则返回 true
        return isIpad || isAndroidTablet;
    }

}
